package cn.hd01.web.controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import cn.hd01.repository.entity.User;
import cn.hd01.service.UserService;
import cn.hd01.web.auth.Auth;
import cn.hd01.web.auth.AuthType;
import cn.hd01.web.util.WebConstant;

@Controller
@Auth
public class LoginController {

	@Autowired
	private UserService service;

	@RequestMapping(path = { "", "/", "/index" }, method = RequestMethod.GET)
	public String index() {
		return "index";
	}

	@Auth(AuthType.OFF)
	@RequestMapping(path = WebConstant.LOGIN_URL, method = RequestMethod.GET)
	public String login() {
		return "login";
	}

	@RequestMapping(path = "/logout", method = RequestMethod.GET)
	public String logout(HttpSession session) {
		session.removeAttribute(WebConstant.USER_SESSION_NAME);
		return "redirect:" + WebConstant.LOGIN_URL;
	}

	@Auth(AuthType.OFF)
	@RequestMapping(path = WebConstant.LOGIN_URL, method = RequestMethod.POST)
	public ModelAndView toLogin(User u, HttpSession session) {
		User user = service.find(u.getName(), u.getPassword());

		if (user != null) {
			session.setAttribute(WebConstant.USER_SESSION_NAME, user);
			return new ModelAndView("redirect:/index");
		}

		return new ModelAndView("login", "message", "用户名或者密码错误！");
	}
}
